<?php

class Manage_login extends CI_Model {

    function __construct(){
        parent::__construct();
        $this->load->model('get_profile_infos');
        $this->load->model('manage_session');
        $fb_config = array(
            'appId'  => '264489850252668',
            'secret' => '150cc65835eb81c20faa114175539758',
            'cookie' => true,
        );
        $this->load->library('facebook', $fb_config);
    }

    function manageLogin(){

        $this->checkAvailSessionCookies();
        if($this->input->cookie('LEAPSESSID', TRUE)){
            if($this->input->cookie('LEAPSESSIF') === 'FACEBOOK'){
                $data = $this->GetFacebookUsers();
            }
            if($this->input->cookie('LEAPSESSIF') === 'TWITTER'){
                $data = $this->GetTwitterUserInfos();
            }
            if($this->input->cookie('LEAPSESSIF') === 'LEAP'){
                $data = $this->get_profile_infos->getInfosID($this->input->cookie('LEAPSESSID'));
            }
        }else{
            $data = $this->login();
        }
        return $data;
    }

    function login(){
        
            $loginOptions = array(
                'domain'=>'http://www.leapdemo.com',
                'scope' => 'email,user_about_me,publish_actions',
                'display' => 'popup',
                'redirect_uri' => 'http://leapdemo.com/login/loginFacebook',

            );
            
            $data['login_url_facebook'] = $this->facebook->getLoginUrl($loginOptions);
            
        return $data;
    }
    
    function GetFacebookUsers(){
        $user = $this->facebook->getUser();
        if(!$user){
            $this->redirectIfNotLoggeind();
        }
        if ($user) {
            try {
                $data['user_profile'] = $this->facebook->api('/me');
                $data = $this->setupFacebookUsers($data['user_profile']);
            } catch (FacebookApiException $e) {
                $user = null;
            }
        }else {
            if($this->session->userdata('LEAPSESS'))
                $this->session->sess_destroy();
            }

        if ($user) {
            
            $data['logout_url_facebook'] = $this->facebook->getLogoutUrl();
            return $data;
        }
    }
    function GetTwitterUserInfos() {
        $this->load->library('tweet');
        $this->tweet->get_tokens();
        
        if ($this->tweet->logged_in()) {
            
            $user = $this->tweet->call('get', 'account/verify_credentials');
            $user = $this->get_profile_infos->getInfosID($user->id);
            
            return $user;
            
        }else{
            $this->redirectIfNotLoggeind();
        }
    }
    function setupFacebookUsers($user){
        
        $this->mongo_db->where('user_id', $user['id']);
        $query = $this->mongo_db->get('community');
        
        if (!isset ($query[0])) {
            
            $data = array(
                "user_id" => $user["id"],
                "first_name" => $user["first_name"],
                "last_name" => $user["last_name"],
                "username" => $user["username"],
                "email_address" => $user["email"],
                "profile_pic" => "https://graph.facebook.com/" . $user["id"] . "/picture?type=large",
                "profile_pic_thumb" => "https://graph.facebook.com/" . $user["id"] . "/picture",
                'birthday_month' => "",
                'birthday_day' => "",
                'birthday_year' => "",
                'about' => "",
                'mood' => "",
                'password' =>'',
                'sex' => "",
                'city' => "",
                'state' => "",
                'country' => "",
                'team' => "",
                'height' => "",
                'weight' => "",
                'tracer' => "",
                'shoe' => "",
                'spot' => "",
                'website' => "",
                'facebook' => "",
                'twitter' => "",
                'googleplus' => "",
                'flickr' => "",
                'follow' => array(),
                'skype' => "",
                'profile_cover' => "",
                "profile_cover_pos"=> "",
            );
            
            $insert = $this->mongo_db->insert('community', $data);

            return $data;
        }else{
            $this->updateFacebookData($user, $query[0]);
            $this->mongo_db->where(array('user_id_to' => (string)$user['id'],'status' => 'new'));
            $notification = $this->mongo_db->get('notifications');
            $query[0]['notification'] = $notification;
            return $query[0];
        }
    }
    function setupTwitterUsers($user){
        
        $this->mongo_db->where('user_id', $user["user_id"]);
        $query = $this->mongo_db->get('community');
        
        if (!isset ($query[0])) {
            
            $data = array(
                "user_id" => $user["id_str"],
                "first_name" => $user["first_name"],
                "last_name" => $user["last_name"],
                "username" => $user["screen_name"],
                "email_address" => $user["email_adress"],
                "profile_pic" => "",
                "profile_pic_thumb" => $user["profile_image_url_https"],
                'birthday_month' => "",
                'birthday_day' => "",
                'birthday_year' => "",
                'about' => "",
                'mood' => "",
                'sex' => "",
                'city' => "",
                'state' => "",
                'password' =>'',
                'country' => "",
                'height' => "",
                'weight' => "",
                'tracer' => "",
                'shoe' => "",
                'team' => "",
                'spot' => "",
                'website' => "",
                'facebook' => "",
                'twitter' => "",
                'googleplus' => "",
                'flickr' => "",
                'skype' => "",
                'follow' => array(),
                'profile_cover' => "",
                "profile_cover_pos"=> "",
            );
            $insert = $this->mongo_db->insert('community', $data);
        }else{
            $this->mongo_db->where(array('user_id_to' => (string)$user["user_id"],'status' => 'new'));
            $notification = $this->mongo_db->get('notifications');
            $query[0]['notification'] = $notification;
            return $query[0];
        }
    }
    
    function updateFacebookData($user,$query){
            if($user["first_name"] != $query["first_name"]){
                $this->updateData("first_name",$user["first_name"], $query["user_id"]);
            }
            if($user["email"] != $query["email_address"]){
                $this->updateData("email_address",$user["email"], $query["user_id"]);
            }
            if($user["last_name"] != $query["last_name"]){
                $this->updateData("last_name",$user["last_name"], $query["user_id"]);
            }
            if($user["username"] != $query["username"]){
                $this->updateData("username",$user["username"], $query["user_id"]);
            }
    }

    function updateData($key,$value,$user_id){
        $data = array($key => $value);
        $this->mongo_db->where('user_id' , (string)$user_id);
        $query = $this->mongo_db->set($data)->update('community');
        return  $query;
    }

    function checkAvailSessionCookies(){
        if($this->input->cookie('LEAPSESSIF') && !$this->session->userdata('loggedIn')){
            $this->manage_session->leapSession($this->input->cookie('LEAPSESSID'),$this->input->cookie('LEAPSESSIF'));
        }
    }
    function redirectIfNotLoggeind() {
        delete_cookie('LEAPSESSID');
        delete_cookie('LEAPSESSIF');
        redirect('/');
    }
}